//
//  ListenPortPacketProcess.m
//  HiQ
//
//  Created by shoguncao on 12-8-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "MainWindowController.h"
#import "ListenPortPacketProcess.h"
#import "MacrosDefine.h"
#import "Buddy.h"
#import "BuddyGroup.h"

@implementation ListenPortPacketProcess

- (void)sendListenPortPacket
{
    // 不发送 ip
    Buddy *myself = [[MainWindowController sharedMainWindowController] myselfInfo];
    
    NSInteger hrdLen = sizeof(LISTENPORTHRD);
    
    LISTENPORTHRD *hrd = (LISTENPORTHRD *)NewPtr(hrdLen);
    hrd->type = CMD_FUN_LISTENPORT;
    hrd->operation = 0; // 任意数值
    hrd->userId = myself.buddyQQ;
    hrd->listenPort = myself.listenPort;
    hrd->ip_len = 0;
    
    NSInteger sendLen = hrdLen - sizeof(NSInteger)*2;   // 减掉 type 和 operation 的长度
    NSData *sendData = [[NSData alloc] initWithBytes:(char *)&(hrd->userId) length:sendLen];
    [[Connection sharedServerConnection] sendData:sendData cmd:hrd->type subcmd:hrd->operation];
    
    DisposePtr((char *)hrd);
}

- (void)onReceiveListPortPacket:(NSData *)data
{
    LISTENPORTHRD *hrd = (LISTENPORTHRD *)[data bytes];
    
    BuddyListSource *buddyListSource = [[MainWindowController sharedMainWindowController] buddySource];
    NSMutableArray *buddyGroupArray = [buddyListSource buddyGroupArray];
    BuddyGroup *firstBuddyGroup = [buddyGroupArray objectAtIndex:0];
    NSMutableArray *buddyList = firstBuddyGroup->buddyList;
    
    for (NSInteger i=0; i<[buddyList count]; ++i)
    {
        Buddy *buddy = [buddyList objectAtIndex:i];
        if (buddy.buddyQQ == hrd->userId)
        {
            buddy.listenPort = hrd->listenPort;
            char *ipChar = (char *)hrd + sizeof(LISTENPORTHRD);
            NSData *ipData = [[NSData alloc] initWithBytes:ipChar length:hrd->ip_len];
            NSString *ipStr = [NSKeyedUnarchiver unarchiveObjectWithData:ipData];
            buddy.ip = ipStr;
        }
    }
}

@end
